package com.example.ying.service.impl;

import com.example.ying.common.R;
import com.example.ying.common.utils.RedisUtil;
import com.example.ying.model.LoginAdmin;
import com.example.ying.model.request.AdminRequest;
import com.example.ying.service.LoginServcie;
import com.example.ying.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginServcie {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public R userLogin(AdminRequest adminRequest) {
        return null;
    }

    @Override
    public R adminLogin(AdminRequest adminRequest) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(adminRequest.getUsername(),adminRequest.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginAdmin loginAdmin = (LoginAdmin) authenticate.getPrincipal();
        String adminId = loginAdmin.getAdmin().getId().toString();
        //String adminName = loginAdmin.getAdmin().getName();
        String jwt = JwtUtil.createJWT(adminId);
        //authenticate存入redis
        redisUtil.setCacheObject("login:"+adminId,loginAdmin);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return R.success("登陆成功", map);
    }

    @Override
    public R adminLogout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginAdmin loginAdmin = (LoginAdmin) authentication.getPrincipal();
        String adminId = loginAdmin.getAdmin().getId().toString();
        redisUtil.deleteObject("login:"+adminId);
        return R.success("退出成功！");
    }
}


